//
//  QLMEditLocationVC.m
//  Xiaomakuaixiu
//
//  Created by 龚碧容 on 2017/10/7.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "QLMEditLocationVC.h"
#import "QLMEditTabCell.h"

#import "QLMADetailAddressVC.h"

@interface QLMEditLocationVC ()<UITableViewDelegate,UITableViewDataSource,QLMEditTabCellDelegate>{
    QLMEditTabCell *editcell;
    QLMCustomTipView *tipView;
    NSInteger currentPage;
}

@property (nonatomic,strong) UITableView *tableview;
@property (nonatomic,strong) UIButton *selectButton;
@property (nonatomic,strong) NSMutableArray *selectedArray;

@property (nonatomic,strong) NSMutableArray *addressDataArray;

@end

@implementation QLMEditLocationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title=@"地址管理";
    self.view.backgroundColor=UIColorFromRGB(0xf5f5f5);
    
    currentPage=1;
    _addressDataArray=[NSMutableArray array];
    _selectedArray=[NSMutableArray array];
    
    CGRect tabFrame = CGRectMake(0, 0, kScreen_width, kScreen_height-QLM_StatusBarAndNavigationBarHeight-40);
    
    _tableview=[[UITableView alloc] initWithFrame:tabFrame style:UITableViewStyleGrouped];
    _tableview.backgroundColor=[UIColor clearColor];
    _tableview.delegate=self;
    _tableview.dataSource=self;
    _tableview.userInteractionEnabled=YES;
    _tableview.tableFooterView=[UIView new];
    [self.view addSubview:_tableview];
    
    //上拉刷新
    _tableview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestAddresData)];
    _tableview.mj_footer.automaticallyHidden = YES;
    
    tipView=[QLMCustomTipView sharedInstance];
    tipView.hidden = YES;
    [_tableview addSubview:tipView];
    
    UIButton *addButton=[self ecreatButton:CGRectMake(0, kScreen_height-QLM_StatusBarAndNavigationBarHeight-40-IOS11_OR_LATER_SPACE(34), kScreen_width, 40) title:@"+新增地址" image:nil];
    [addButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    addButton.titleLabel.font=[UIFont systemFontOfSize:18.0f];
    addButton.tag=1910;
    addButton.backgroundColor=kButtonColor;
    [self.view addSubview:addButton];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
    [self requestAddresData];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    [self.addressDataArray removeAllObjects];
    [_selectedArray removeAllObjects];
    currentPage=1;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -获取数据
- (void)requestAddresData{
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    if ([token length]==0) {
        return;
    }
    NSDictionary *tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    
    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:[NSString stringWithFormat:@"%ld",currentPage] forKey:@"page"];
    [paramerDic setObject:@"10" forKey:@"rows"];
    
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/rest/listAllAddress" withParamers:paramerDic andBody:tokenDic
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        [_tableview.mj_footer endRefreshing];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            
                            [self.addressDataArray addObjectsFromArray:[responseObject[@"data"] objectForKey:@"list"]];

                            if (self.addressDataArray.count==0) {
                                tipView.hidden = NO;
                            }else{
                                if ([[responseObject[@"data"] objectForKey:@"list"] count]<10) {
                                    _tableview.mj_footer.state = MJRefreshStateNoMoreData;
                                }
                                tipView.hidden = YES;
                                currentPage++;
                            }
                            
                            for (int i=0; i<[[responseObject[@"data"] objectForKey:@"list"] count]; i++) {
                                NSString *isDefaultStr = [[responseObject[@"data"] objectForKey:@"list"][i] objectForKey:@"isDefault"];
                                
                                [_selectedArray addObject:isDefaultStr];
                            }
                            
                            [_tableview reloadData];
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                        
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                        [_tableview.mj_footer endRefreshing];
                    }
     ];
}

#pragma mark - Action
- (UIButton *)ecreatButton:(CGRect)aFrame title:(NSString *)aTitle image:(NSString *)imageName{
    
    UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
    newButton.frame = aFrame;
    [newButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [newButton setTitle:aTitle forState:UIControlStateNormal];
    [newButton setTitleColor:UIColorFromRGB(0x666666) forState:UIControlStateNormal];
    newButton.backgroundColor = [UIColor clearColor];
    newButton.titleLabel.font=[UIFont systemFontOfSize:16.0f];
    [newButton addTarget:self action:@selector(eButtonAction:) forControlEvents:UIControlEventTouchUpInside];

    newButton.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    newButton.titleEdgeInsets = UIEdgeInsetsMake(0, 5, 0, 0);
    
    return newButton;
}

- (void)eButtonAction:(UIButton *)btn{
    if (btn.tag==9000) {
    }else if(btn.tag==1910){
        [self _addClick];
    }
}

- (void)_addClick{
    __weak QLMEditLocationVC *weakself = self;
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [self addActionTarget:alert title:@"地图选点" color:UIColorFromRGB(0x157efb) action:^(UIAlertAction *action) {
        [weakself pustToSelectAddressVC:NO andItemTag:0];
    }];
    [self addActionTarget:alert title:@"手动填写" color:UIColorFromRGB(0x157efb) action:^(UIAlertAction *action) {
        [weakself pustToEditChangeVC:NO andItemTag:0];
    }];
    [self addCancelActionTarget:alert title:@"取消"];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - UIActionSheet delegate
-(void)addCancelActionTarget:(UIAlertController*)alertController title:(NSString *)title{
    UIAlertAction *action = [UIAlertAction actionWithTitle:title style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
    }];
    
    if (IOS9_OR_LATER) {
        [action setValue:UIColorFromRGB(0x157efb) forKey:@"_titleTextColor"];
    }
    
    [alertController addAction:action];
}

- (void)addActionTarget:(UIAlertController *)alertController title:(NSString *)title color:(UIColor *)color action:(void(^)(UIAlertAction *action))actionTarget{
    UIAlertAction *action = [UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        actionTarget(action);
    }];
    
    if (IOS9_OR_LATER) {
        [action setValue:color forKey:@"_titleTextColor"];
    }
    
    [alertController addAction:action];
}

#pragma mark - QLMEditTabCellDelegate
- (void)_deleteAddressAction:(NSInteger)indextag{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定要删除吗？" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              [self _setupDeleteUserAddressId:indextag];
                                                          }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault
                                                         handler:^(UIAlertAction * action) {
                                                         }];
    
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)_editAddressAction:(NSInteger)indextag{
    
    __weak QLMEditLocationVC *weakself = self;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [self addActionTarget:alert title:@"地图选点" color:UIColorFromRGB(0x157efb) action:^(UIAlertAction *action) {
        [weakself pustToSelectAddressVC:YES andItemTag:indextag];
    }];
    [self addActionTarget:alert title:@"手动填写" color:UIColorFromRGB(0x157efb) action:^(UIAlertAction *action) {
        [weakself pustToEditChangeVC:YES andItemTag:indextag];
    }];
    [self addCancelActionTarget:alert title:@"取消"];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)pustToEditChangeVC:(BOOL)isEditable andItemTag:(NSInteger)indexTag{
    
    QLMADetailAddressVC *detailAddressVC=[QLMADetailAddressVC new];
    detailAddressVC.isEditable=isEditable;
    
    if (isEditable) {
        
        NSString *addressKey = [self.addressDataArray[indexTag] objectForKey:@"addressKey"];
        NSString *addressVal = [self.addressDataArray[indexTag] objectForKey:@"addressVal"];
        NSString *addressLatitude = [self.addressDataArray[indexTag] objectForKey:@"addressLatitude"];
        NSString *addressLongitude = [self.addressDataArray[indexTag] objectForKey:@"addressLongitude"];
        NSString *userAddressId = [self.addressDataArray[indexTag] objectForKey:@"userAddressId"];
        
        detailAddressVC.addressInfoDic=[NSDictionary dictionaryWithObjectsAndKeys:addressKey,@"addressProvince",addressVal,@"addressVal",addressLatitude,@"latitude",addressLongitude,@"longitude",userAddressId,@"userAddressId", nil];
    }
    
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:detailAddressVC animated:YES];
}

- (void)pustToSelectAddressVC:(BOOL)isEditBool andItemTag:(NSInteger)indexRow{
    SelectAddressViewController *selectAddrVC=[SelectAddressViewController new];
    [selectAddrVC returnText:^(NSString *addressInfo, NSDictionary *addressDetailDic) {}];
    
    if (isEditBool) {
        selectAddrVC.isEditable=YES;
        NSString *userAddressId = [self.addressDataArray[indexRow] objectForKey:@"userAddressId"];
        selectAddrVC.addressIdStr = userAddressId;
        
        NSString *addressKey = [self.addressDataArray[indexRow] objectForKey:@"addressKey"];
        NSString *addressVal = [self.addressDataArray[indexRow] objectForKey:@"addressVal"];
        NSString *totalStr=[NSString stringWithFormat:@"%@%@",addressKey,addressVal];
        
        selectAddrVC.addressDetailStr=totalStr;
    }
    
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:selectAddrVC animated:YES];
}

#pragma mark - UITableView dtasource
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footerView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 10)];
    footerView.backgroundColor=[UIColor clearColor];
    footerView.userInteractionEnabled=YES;
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *headerView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 30)];
    headerView.backgroundColor=UIColorFromRGB(0xf5f5f5);
    headerView.userInteractionEnabled=YES;
    return headerView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.addressDataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    editcell=[QLMEditTabCell cellWithTableView:tableView];
    editcell.delegate=self;
    editcell.userInteractionEnabled=YES;
    editcell.deleteBtn.tag=indexPath.section;
    editcell.editBtn.tag=indexPath.section;
    editcell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    NSString *addressValStr=nil;
    NSString *addressKey=nil;
    if (self.addressDataArray.count!=0) {
        addressValStr=[self.addressDataArray[indexPath.section] objectForKey:@"addressVal"];
        addressKey=[self.addressDataArray[indexPath.section] objectForKey:@"addressKey"];
        editcell.addressDetailLabel.text=[NSString stringWithFormat:@"%@",addressKey];
        editcell.addressValLabel.text=[NSString stringWithFormat:@"%@",addressValStr];
    }
    
    if ([_selectedArray[indexPath.section] boolValue]) {
        NSString *tmpAddre=[NSString stringWithFormat:@"%@%@",addressKey,addressValStr];
        [[NSUserDefaults standardUserDefaults] setObject:tmpAddre forKey:kDefaultAddress];
        
        NSString *latititudeStr=[self.addressDataArray[indexPath.section] objectForKey:@"addressLatitude"];
        NSString *longtitudeStr=[self.addressDataArray[indexPath.section] objectForKey:@"addressLongitude"];
        NSDictionary *enddic=[NSDictionary dictionaryWithObjectsAndKeys:latititudeStr,@"latitu",longtitudeStr,@"longtitu", nil];
        [[NSUserDefaults standardUserDefaults] setObject:enddic forKey:kDefaultEnddic];
        
        [editcell.morenAddrBtn setImage:[UIImage imageNamed:@"selected"] forState:UIControlStateNormal];
    }else{
        [editcell.morenAddrBtn setTitle:@"设为默认地址" forState:UIControlStateNormal];
        [editcell.morenAddrBtn setImage:[UIImage imageNamed:@"unselected"] forState:UIControlStateNormal];
    }
    
    return editcell;
}

#pragma mark - UITableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.isCannotEdit) {
    
        NSString *tmpaddressKey = [self.addressDataArray[indexPath.section] objectForKey:@"addressKey"];
        NSString *tmpaddressVal = [self.addressDataArray[indexPath.section] objectForKey:@"addressVal"];
        
        NSString *addressStr = [NSString stringWithFormat:@"%@%@",tmpaddressKey,tmpaddressVal];
        NSString *latititudeStr=[self.addressDataArray[indexPath.section] objectForKey:@"addressLatitude"];
        NSString *longtitudeStr=[self.addressDataArray[indexPath.section] objectForKey:@"addressLongitude"];
        self.block(addressStr, latititudeStr, longtitudeStr);
        [self.navigationController popViewControllerAnimated:YES];
    }else{
    
        for (int i=0; i<_addressDataArray.count; i++) {

            if (i==indexPath.section) {

                NSString *userAddressIdStr = [self.addressDataArray[indexPath.section] objectForKey:@"userAddressId"];

                if ([_selectedArray[indexPath.section] boolValue]) {
                    [_selectedArray replaceObjectAtIndex:indexPath.section withObject:@(0)];
                    [editcell.morenAddrBtn setImage:[UIImage imageNamed:@"unselected"] forState:UIControlStateNormal];

                    [self _setupDefaultAddressWithUserAddressId:userAddressIdStr andOp:@"0"];
                }else{
                    [_selectedArray replaceObjectAtIndex:indexPath.section withObject:@(1)];
                    [editcell.morenAddrBtn setImage:[UIImage imageNamed:@"selected"] forState:UIControlStateNormal];

                    [self _setupDefaultAddressWithUserAddressId:userAddressIdStr andOp:@"1"];
                }

            }else{
                [_selectedArray replaceObjectAtIndex:i withObject:@(0)];
                [editcell.morenAddrBtn setImage:[UIImage imageNamed:@"unselected"] forState:UIControlStateNormal];
            }
        }
        
        [_tableview reloadData];
    }
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
#pragma mark - http
- (void)_setupDefaultAddressWithUserAddressId:(NSString *)userAddressId andOp:(NSString *)op{
    
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSDictionary *tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    if ([token length]==0) {
        return;
    }
    
    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:userAddressId forKey:@"userAddressId"];
    [paramerDic setObject:op forKey:@"op"];
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/rest/setDefaultAddress" withParamers:paramerDic andBody:tokenDic
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            if ([op isEqualToString:@"0"]) {
                                [[NSUserDefaults standardUserDefaults] removeObjectForKey:kDefaultAddress];
                                [[NSUserDefaults standardUserDefaults] removeObjectForKey:kDefaultEnddic];
                            }
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (void)_setupDeleteUserAddressId:(NSInteger)aIndextag{
    
    NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
    NSDictionary *tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
    
    NSString *userAddressIdStr = [self.addressDataArray[aIndextag] objectForKey:@"userAddressId"];
    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:userAddressIdStr forKey:@"userAddressId"];

    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/rest/deleteAddress" withParamers:paramerDic andBody:tokenDic
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            
                            NSString *addStr=[[NSUserDefaults standardUserDefaults] objectForKey:kDefaultAddress];
                            if (addStr.length!=0) {
                                if ([_selectedArray[aIndextag] boolValue]) {
                                    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kDefaultAddress];
                                    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kDefaultEnddic];
                                }
                            }
                            
                            [_selectedArray removeObjectAtIndex:aIndextag];
                            [self.addressDataArray removeObjectAtIndex:aIndextag];
                            [_tableview deleteSections:[NSIndexSet indexSetWithIndex:aIndextag] withRowAnimation:UITableViewRowAnimationAutomatic];
                            [_tableview reloadData];
                            
                            if (self.addressDataArray.count==0) {
                                tipView.hidden = NO;
                            }else{
                                tipView.hidden = YES;
                            }

                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

@end
